const express = require('express');
const router = express.Router();
const db = require('../config/database');
const { validatePagination } = require('../utils/validation');
const qiniu = require('qiniu');
const axios = require('axios');
const path = require('path');

// 七牛云配置
const qiniuConfig = {
  regionId: 'z0',
  oss: 'qiniuyun',
  bucket: '3d-app',
  domain: 'http://3d-app-qiniu.dlmu.cc',
  qiniuConfig: {
    accessKey: 'XY7NulclFTE8ff15ORUTq-zRFhrfnSOxwnrGF6e7',
    secretKey: '3Pqaeoh1JmmSdhfpONLE3LcH6HJsl3Y2vl8lT-0D',
  },
  catePathSplit: '/design/',
};

// 初始化七牛云
const mac = new qiniu.auth.digest.Mac(qiniuConfig.qiniuConfig.accessKey, qiniuConfig.qiniuConfig.secretKey);
const config = new qiniu.conf.Config();
const bucketManager = new qiniu.rs.BucketManager(mac, config);

// 上传文件到七牛云
async function uploadToQiniu(fileUrl, fileName) {
  try {
    // 下载原文件
    const response = await axios({
      method: 'GET',
      url: fileUrl,
      responseType: 'arraybuffer'
    });

    // 生成七牛云的文件名
    const ext = path.extname(fileName);
    const key = `${qiniuConfig.catePathSplit}${Date.now()}${ext}`;

    // 上传到七牛云
    return new Promise((resolve, reject) => {
      bucketManager.put(
        Buffer.from(response.data),
        key,
        qiniuConfig.qiniuConfig.accessKey,
        {
          mimeType: response.headers['content-type']
        },
        (err, respBody, respInfo) => {
          if (err) {
            reject(err);
          } else {
            resolve(`${qiniuConfig.domain}${key}`);
          }
        }
      );
    });
  } catch (error) {
    console.error('上传文件到七牛云失败:', error);
    throw error;
  }
}

// 获取素材列表
router.get('/', async (req, res) => {
  try {
    const { 
      page = 1, 
      pageSize = 20, 
      search,
      populate,
      'filters[material_type][$eq]': typeId,
      'populate[img]': populateImg
    } = req.query;
    
    // 验证分页参数
    const { error } = validatePagination({ page: parseInt(page), pageSize: parseInt(pageSize) });
    if (error) {
      return res.status(400).json({ error: error.details[0].message });
    }
    
    // 确保参数为有效数字
    const pageNum = Math.max(1, parseInt(page) || 1);
    const pageSizeNum = Math.max(1, parseInt(pageSize) || 20);
    const offset = (pageNum - 1) * pageSizeNum;
    
    // 构建查询条件
    let whereClause = 'WHERE m.is_public = TRUE';
    const params = [];
    
    if (typeId) {
      whereClause += ' AND m.type_id = ?';
      params.push(Math.max(1, parseInt(typeId) || 1));
    }
    
    if (search) {
      whereClause += ' AND m.name LIKE ?';
      params.push(`%${search}%`);
    }
    
    // 查询总数
    const [countResult] = await db.query(
      `SELECT COUNT(*) as total FROM materials m ${whereClause}`,
      params
    );
    const total = countResult[0].total;
    
    // 查询数据
    const query = `
      SELECT 
        m.id,
        m.name,
        m.type_id,
        m.url,
        m.thumbnail,
        m.width,
        m.height,
        m.file_size,
        m.file_type,
        m.tags,
        m.download_count,
        m.created_at,
        m.updated_at,
        ${populate === '*' ? 'mt.name as type_name' : 'NULL as type_name'}
      FROM materials m
      ${populate === '*' ? 'LEFT JOIN material_types mt ON m.type_id = mt.id' : ''}
      ${whereClause}
      ORDER BY m.created_at DESC
      LIMIT ? OFFSET ?
    `;
    
    const [rows] = await db.query(query, [...params, pageSizeNum, offset]);
    
    // 格式化数据
    const data = rows.map(row => ({
      id: row.id,
      attributes: {
        name: row.name,
        url: row.url,
        thumbnail: row.thumbnail,
        width: row.width,
        height: row.height,
        file_size: row.file_size,
        file_type: row.file_type,
        tags: row.tags ? JSON.parse(row.tags) : [],
        download_count: row.download_count,
        createdAt: row.created_at,
        updatedAt: row.updated_at,
        ...(populate === '*' && row.type_name && {
          material_type: {
            data: {
              id: row.type_id,
              attributes: {
                name: row.type_name
              }
            }
          }
        }),
        ...(populateImg === '*' && {
          img: {
            data: {
              id: row.id,
              attributes: {
                url: row.url,
                thumbnail: row.thumbnail
              }
            }
          }
        })
      }
    }));
    
    res.json({
      data,
      meta: {
        pagination: {
          page: pageNum,
          pageSize: pageSizeNum,
          pageCount: Math.ceil(total / pageSizeNum),
          total
        }
      }
    });
  } catch (error) {
    console.error('获取素材列表失败:', error);
    res.status(500).json({ error: '获取素材列表失败' });
  }
});

// 获取单个素材详情
router.get('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const { populate, 'populate[img]': populateImg } = req.query;
    
    // 确保 id 为有效数字
    const materialId = Math.max(1, parseInt(id) || 1);
    
    const query = `
      SELECT 
        m.*,
        ${populate === '*' ? 'mt.name as type_name' : 'NULL as type_name'}
      FROM materials m
      ${populate === '*' ? 'LEFT JOIN material_types mt ON m.type_id = mt.id' : ''}
      WHERE m.id = ? AND m.is_public = TRUE
    `;
    
    const [rows] = await db.query(query, [materialId]);
    
    if (rows.length === 0) {
      return res.status(404).json({ error: '素材不存在' });
    }
    
    const row = rows[0];
    const data = {
      id: row.id,
      attributes: {
        name: row.name,
        url: row.url,
        thumbnail: row.thumbnail,
        width: row.width,
        height: row.height,
        file_size: row.file_size,
        file_type: row.file_type,
        tags: row.tags ? JSON.parse(row.tags) : [],
        download_count: row.download_count,
        createdAt: row.created_at,
        updatedAt: row.updated_at,
        ...(populate === '*' && row.type_name && {
          material_type: {
            data: {
              id: row.type_id,
              attributes: {
                name: row.type_name
              }
            }
          }
        }),
        ...(populateImg === '*' && {
          img: {
            data: {
              id: row.id,
              attributes: {
                url: row.url,
                thumbnail: row.thumbnail
              }
            }
          }
        })
      }
    };
    
    // 增加下载次数
    await db.query(
      'UPDATE materials SET download_count = download_count + 1 WHERE id = ?',
      [materialId]
    );
    
    res.json({ data });
  } catch (error) {
    console.error('获取素材详情失败:', error);
    res.status(500).json({ error: '获取素材详情失败' });
  }
});

// 上传素材
router.post('/', async (req, res) => {
  try {
    const { name, type_id, url, thumbnail, width, height, file_size, file_type, tags } = req.body;
    
    // 上传原图到七牛云
    const qiniuUrl = await uploadToQiniu(url, name);
    
    // 上传缩略图到七牛云
    const qiniuThumbnail = await uploadToQiniu(thumbnail, `thumb_${name}`);
    
    // 保存到数据库
    const [result] = await db.query(
      `INSERT INTO materials (
        name, type_id, url, thumbnail, width, height, 
        file_size, file_type, tags, is_public, created_at, updated_at
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, TRUE, NOW(), NOW())`,
      [
        name,
        type_id,
        qiniuUrl,
        qiniuThumbnail,
        width,
        height,
        file_size,
        file_type,
        JSON.stringify(tags || [])
      ]
    );
    
    res.json({
      data: {
        id: result.insertId,
        attributes: {
          name,
          url: qiniuUrl,
          thumbnail: qiniuThumbnail,
          width,
          height,
          file_size,
          file_type,
          tags: tags || [],
          createdAt: new Date(),
          updatedAt: new Date()
        }
      }
    });
  } catch (error) {
    console.error('上传素材失败:', error);
    res.status(500).json({ error: '上传素材失败' });
  }
});

module.exports = router;